package com.atguigu.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * public <U> CompletableFuturecU> thenApply(Function<? super T,? extends U> fn)
 * public <U> Completab1eFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
 * public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn，
                                                    Executor executor)
 * public completionstage<Void> thenAccept(Consumer<? super T> action);
 * public completionStage<Void> thenAcceptAsync(Consumer<? super T> action);
 * public CompletionStagecVoid> thenAcceptAsync(Consumer<? super T> action,Executor
 * executor);
 * public Completionstage<Void> thenRun(Runnable action);
 * public Completionstage<Void> thenRunAsync(Runnable action);
 * public completionStage<Void> thenRunAsync(Runnable action,Executor executor);
 */

public class ThreadTest2 {
    public static ExecutorService excutor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main start ....");
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(ThreadTest2::task, excutor)
                .whenComplete(ThreadTest2::accept)  // 完成后的感知
                .exceptionally(ThreadTest2::apply)
                .handle(ThreadTest2::handle)  // 方法执行完毕后的处理
                .thenApply(ThreadTest2::thenApply);
        System.out.println("main end.... 返回值：" + future.get());
    }

    public static int thenApply(Integer result) {
        /**
         * thenApply有返回值
         */
        System.out.println("任务2启动   ： 1 + 1 = ");
        System.out.println("任务2获取任务1的结果：" + result);
        return 2;
    }

    public static int handle(Integer result, Throwable exception) {
        System.out.println("获取任务1的结果：" + result);
        System.out.println("获取任务1的异常：" + exception);
        System.out.println("异常不会传播，前面调用exceptionally方法处理了异常");
        return 200;
    }

    public static int apply(Throwable exception) {
        System.out.println("获取任务1的异常，并提供一个默认返回值" + exception);
        return 100;
    }


    public static void accept(Integer result, Throwable exception) {
        System.out.println("获取任务1的结果：" + result);
        System.out.println("获取任务1的异常：" + exception);
    }

    public static int task() {
        System.out.println("任务1启动   ： 10 / 0");
        return 10 / 0;
    }
}
